package work.jame.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import work.jame.blog.framework.constant.UserConfigurationConstant;
import work.jame.blog.framework.exception.BusinessException;
import work.jame.blog.framework.exception.db.InsertDataBaseException;
import work.jame.blog.framework.utils.security.SpringSecurityUtils;
import work.jame.blog.pojo.UserConfiguration;
import work.jame.blog.mapper.UserConfigurationMapper;
import work.jame.blog.service.UserConfigurationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import work.jame.blog.service.UserWallpaperRelationService;

import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Jame
 * @since 2023-05-15
 */
@Service
public class UserConfigurationServiceImpl extends ServiceImpl<UserConfigurationMapper, UserConfiguration> implements UserConfigurationService {

    @Autowired
    private UserWallpaperRelationService userWallpaperRelationService;


    @Override
    public UserConfiguration queryUserConfigurationByUserId(Long userId) {
        QueryWrapper<UserConfiguration> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return this.getOne(wrapper);
    }

    @Override
    public UserConfiguration getCurrentLoginUserConfiguration() {
        Long userId = SpringSecurityUtils.getCurrentLoginUserId();
        return this.queryUserConfigurationByUserId(userId);
    }

    @Override
    public void saveUserDefaultConfiguration(Long userId) {
        UserConfiguration userConfiguration = new UserConfiguration();
        userConfiguration.setUserId(userId);
        userConfiguration.setNewIpLoginOperation(UserConfigurationConstant.NEW_IP_LOGIN_SEND_EMAIL);
        userConfiguration.setCallMeOperation(UserConfigurationConstant.CALL_ME_SEND_MESSAGE);
        if (!this.save(userConfiguration)) {
            throw new InsertDataBaseException("保存用户配置数据失败");
        }
    }

    @Override
    public boolean updateUserConfiguration(UserConfiguration userConfiguration) {
        Long userId = SpringSecurityUtils.getCurrentLoginUserId();
        //检查当前用户是否购买了该壁纸
        Long wallpaperId = userConfiguration.getUseWallpaperId();
        if (!Objects.isNull(wallpaperId)) {
            if (!userWallpaperRelationService.queryUserHaveWallpaper(userId, wallpaperId)) {
                throw new BusinessException("该壁纸你还没有购买哦");
            }
        }
        QueryWrapper<UserConfiguration> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return this.update(userConfiguration, wrapper);
    }
}
